package com.learn.client;

import com.learn.config.RpcEncoder;
import com.learn.handler.UserClientHandler;
import com.learn.pojo.RpcRequest;
import com.learn.utils.JSONSerializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

/**
 * @program: rmi
 * @description
 * @author: luffy
 * @create: 2020-08-17 14:11
 */
public class RPCConsumer {
    private static final String PROVIDER_NAME = "UserService#sayHello#";

    //1.创建一个线程池对象 --处理我们自定义事件
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());


    //2.声明一个自定义事件处理器 userClientHandler
    private static UserClientHandler userClientHandler;

    //3.编写方法，初始化客户端（创建连接池 bootStrap 设置bootstrap 连接服务器）

    public static void initClient() throws InterruptedException {
        //1.初始化ClientHandler
        userClientHandler = new UserClientHandler();
        //2.创建连接池
        EventLoopGroup group = new NioEventLoopGroup();
        //3.创建客户端的引导对象
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设置编码
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });
        //连接服务端
        bootstrap.connect("127.0.0.1", 8999).sync();

    }

    //4.编写一个方法，使用jdk的动态代理创建对象

    /**
     *
     * @param serviceClass： 接口类型根据那个接口生产子代理对象
     * @param  "UserService#sayHello#"
     * @return
     */
    public static Object createProxy(final Class<?> serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //初始化客户端
                if (userClientHandler == null) {
                    initClient();
                }
                //给UserClientHandler 设置param参数
                RpcRequest request = new RpcRequest();
                request.setClassName(serviceClass.getName());
                request.setRequestId("IUserService");
                request.setMethodName("sayHello");
                request.setParameters(args);
                Method sayHello = serviceClass.getMethod("sayHello",String.class);
                Class<?>[] parameterTypes = sayHello.getParameterTypes();
                request.setParameterTypes(parameterTypes);
                userClientHandler.setParam(request);
                //使用线程池，开启一个线程处理call（）写操作，并返回结果
                Object o = executorService.submit(userClientHandler).get();
                //return 结果
                return o;
            }
        });
    }
}
